import { useRef, useState } from 'react';
import { Button, Modal, Upload, message, Tag } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { ProForm, ProFormText, ProFormTextArea, ProFormSlider } from '@ant-design/pro-components';
import { readUrlKnowledge, addDataKnowledge } from '@/services/knowledge';
import StorageManager from '@/utils/StorageManager';
import { isEmpty } from 'lodash';

import type { ProFormInstance } from '@ant-design/pro-components';

import styles from './index.less';

const formItemLayout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 18 },
};

type StoreInfoType = {
  url?: string;
  title?: string;
  text?: string;
  type?: string;
};

type LinkInfoType = {
  title: string;
  text: string;
};

interface Props {
  addVisible: boolean;
  modelTitle: string;
  closeModel: () => void;
  modelItem: any;
  type: 'edit' | 'add';
}

const AddKnowledgeModel: React.FC<Props> = (props) => {
  const { addVisible, modelTitle, modelItem, closeModel } = props;
  const formRef = useRef<ProFormInstance>();
  const [btnLoading, setbtnLoading] = useState(false);
  const [upoloadLoading, setUpoloadLoading] = useState(false);
  const [okBtnLoading, setOkBtnLoading] = useState(false);
  const [comfirmPop, setComfirmPop] = useState(false);
  const [comfirmMsg, setComfirmMsg] = useState('');
  const [storeInfo, setStoreInfo] = useState<StoreInfoType>();
  const [linkInfo, setLinkInfo] = useState<LinkInfoType>();

  // 文件上传成功后--回显文本
  const formatStoreInfo = async (store: any, name: string) => {
    if (store.url && modelItem) {
      setStoreInfo(store);
      formRef.current?.setFieldValue('text', store.text);
    }
    setUpoloadLoading(false);
  };

  // 导入链接
  const daoInDoc = async () => {
    const link = formRef.current?.getFieldValue('link');
    if (isEmpty(link)) {
      message.error('请输入链接！');
    } else {
      setbtnLoading(true);
      const res = await readUrlKnowledge({ url: link });
      const { code, data } = res || {};
      setbtnLoading(false);

      if (!code && data) {
        setLinkInfo(data);
        formRef.current?.setFieldValue('text', data.text);
      }
    }
  };

  // 关闭
  const handleClose = () => {
    setStoreInfo({});
    formRef.current?.resetFields();
    closeModel();
    setOkBtnLoading(false);
  };

  // 确定按钮
  const handleAdd = (replaceSaveBro?: boolean) => {
    formRef.current
      ?.validateFields()
      .then(async (values) => {
        setOkBtnLoading(true);

        let paramsData: any;
        if (modelTitle === '上传文档') {
          paramsData = {
            knowledgeId: Number(modelItem.id),
            url: storeInfo?.url,
            type: 'PDF',
            title: storeInfo?.title,
            text: storeInfo?.text,
            chunkSize: values?.chunkSize,
            replaceSave: replaceSaveBro ? true : false,
          };
        }
        if (modelTitle === '在线编辑') {
          paramsData = {
            knowledgeId: Number(modelItem.id),
            chunkSize: values?.chunkSize,
            type: 'TEXT',
            text: values.text,
            title: values.title,
            replaceSave: replaceSaveBro ? true : false,
            url: values.title,
          };
        }
        if (modelTitle === '导入链接') {
          paramsData = {
            knowledgeId: Number(modelItem.id),
            chunkSize: values?.chunkSize,
            type: 'WORD',
            text: linkInfo?.text,
            title: linkInfo?.title,
            replaceSave: replaceSaveBro ? true : false,
            url: values.link,
          };
        }

        const res = await addDataKnowledge(paramsData);
        if (!res.code && res.data) {
          message.success('新增成功');
          handleClose();
        } else if (res.code && res.code === 40001) {
          setOkBtnLoading(false);
          setComfirmPop(true);
          setComfirmMsg(res.message);
        } else {
          setOkBtnLoading(false);
          message.error(res.message || '新增失败');
        }
      })
      .catch(() => {});

    // if (modelTitle === '上传文档') {
    //   formRef.current
    //     ?.validateFields()
    //     .then(async (values) => {
    //       const paramsData = {
    //         knowledgeId: Number(modelItem.id),
    //         url: storeInfo?.url,
    //         type: 'PDF',
    //         title: storeInfo?.title,
    //         text: storeInfo?.text,
    //         chunkSize: values?.chunkSize,
    //         replaceSave: false,
    //       };
    //       const res = await addDataKnowledge(paramsData);
    //       if (!res.code && res.data) {
    //         message.success('新增成功');
    //       } else {
    //         message.error(res.message || '新增失败');
    //       }

    //       handleClose();
    //     })
    //     .catch(() => {});
    // }
    // if (modelTitle === '在线编辑') {
    //   formRef.current
    //     ?.validateFields()
    //     .then(async (values) => {
    //       const paramsData = {
    //         knowledgeId: Number(modelItem.id),
    //         chunkSize: 500,
    //         type: 'TEXT',
    //         text: values.text,
    //         title: values.title,
    //         replaceSave: false,
    //         url: values.title,
    //       };
    //       const res = await addDataKnowledge(paramsData);
    //       if (!res.code && res.data) {
    //         message.success('新增成功');
    //       } else {
    //         message.error(res.message || '新增失败');
    //       }

    //       handleClose();
    //     })
    //     .catch(() => {});
    // }
    // if (modelTitle === '导入链接') {
    //   formRef.current
    //     ?.validateFields()
    //     .then(async (values) => {
    //       const paramsData = {
    //         knowledgeId: Number(modelItem.id),
    //         chunkSize: 500,
    //         type: 'WORD',
    //         text: linkInfo?.text,
    //         title: linkInfo?.title,
    //         replaceSave: false,
    //         url: values.link,
    //       };
    //       const res = await addDataKnowledge(paramsData);
    //       if (!res.code && res.data) {
    //         message.success('新增成功');
    //       } else {
    //         message.error(res.message || '新增失败');
    //       }
    //       handleClose();
    //     })
    //     .catch(() => {});
    // }
  };

  // 覆盖提示--yes
  const okComformPop = () => {
    setComfirmPop(false);
    handleAdd(true);
  };

  // 覆盖提示--no
  const closeComformPop = () => {
    setComfirmPop(false);
  };

  return (
    <div>
      <Modal
        confirmLoading={okBtnLoading}
        maskClosable={false}
        width={800}
        title={modelTitle}
        open={addVisible}
        onOk={() => handleAdd(false)}
        onCancel={handleClose}
        okText="确认导入"
      >
        {modelTitle === '上传文档' && (
          <div>
            <div style={{ marginTop: '0px', marginBottom: '20px' }}>
              <Upload
                key="Upload"
                action={`apiv2/knowledge/upload`}
                headers={{
                  Authorization: `Bearer ${StorageManager.getLocalStorageSync('token')}`,
                }}
                showUploadList={false}
                accept=".pdf"
                onChange={({ file }) => {
                  setUpoloadLoading(true);
                  if (!file.response?.code && file.response?.data) {
                    formatStoreInfo(file?.response?.data, file.name);
                  }
                }}
              >
                <Button
                  key="button"
                  type="primary"
                  icon={<UploadOutlined />}
                  loading={upoloadLoading}
                >
                  上传文档
                </Button>
              </Upload>
            </div>
            {storeInfo?.title ? (
              <div style={{ marginBottom: '16px' }}>
                <Tag
                  closable
                  onClose={() => {
                    setStoreInfo({});
                    formRef.current?.setFieldValue('text', null);
                  }}
                >
                  {storeInfo.title}
                </Tag>
              </div>
            ) : null}

            {/* 回显文本 */}
            <ProForm
              formRef={formRef}
              {...formItemLayout}
              layout="vertical"
              submitter={false}
              initialValues={{ chunkSize: 500 }}
            >
              <ProFormSlider
                name="chunkSize"
                label="段落长度"
                fieldProps={{ min: 300, max: 1000 }}
                marks={{
                  300: '300',
                  1000: '1000',
                }}
              />
              <ProFormTextArea
                name="text"
                label="文本"
                placeholder=""
                fieldProps={{
                  autoSize: { minRows: 10, maxRows: 10 },
                  style: { overflowY: 'auto' },
                }}
                rules={[
                  {
                    required: true,
                    message: '请上传文本',
                  },
                ]}
              />
            </ProForm>
          </div>
        )}

        {modelTitle === '在线编辑' && (
          <div>
            <ProForm
              formRef={formRef}
              {...formItemLayout}
              layout="horizontal"
              submitter={false}
              initialValues={{ chunkSize: 500 }}
            >
              <ProFormText
                name="title"
                label="标题"
                placeholder="请输入标题"
                // fieldProps={{ maxLength: 20 }}
                rules={[
                  {
                    required: true,
                    message: '请输入标题',
                  },
                  // {
                  //   max: 20,
                  //   message: '名称长度1-20个字符',
                  // },
                ]}
              />

              <ProFormSlider
                name="chunkSize"
                label="段落长度"
                fieldProps={{ min: 300, max: 1000 }}
                marks={{
                  300: '300',
                  1000: '1000',
                }}
              />

              <ProFormTextArea
                name="text"
                label="文本"
                placeholder=""
                fieldProps={{
                  autoSize: { minRows: 12, maxRows: 12 },
                  style: { overflowY: 'auto' },
                }}
                rules={[
                  {
                    required: true,
                    message: '请输入正文',
                  },
                ]}
              />
            </ProForm>
          </div>
        )}

        {modelTitle === '导入链接' && (
          <div>
            <ProForm
              formRef={formRef}
              {...formItemLayout}
              layout="horizontal"
              submitter={false}
              initialValues={{ chunkSize: 500 }}
            >
              <div style={{ display: 'flex' }}>
                <ProFormText
                  labelCol={{ span: 6 }}
                  name="link"
                  label="链接"
                  placeholder="请输入链接"
                  rules={[
                    {
                      required: true,
                      message: '请输入链接',
                    },
                  ]}
                />
                <Button
                  style={{ marginLeft: '20px' }}
                  key="button"
                  type="primary"
                  loading={btnLoading}
                  onClick={() => daoInDoc()}
                >
                  开始导入
                </Button>
              </div>

              <ProFormSlider
                name="chunkSize"
                label="段落长度"
                fieldProps={{ min: 300, max: 1000 }}
                marks={{
                  300: '300',
                  1000: '1000',
                }}
              />
              <ProFormTextArea
                name="text"
                label="文本"
                placeholder=""
                fieldProps={{
                  autoSize: { minRows: 12, maxRows: 12 },
                  style: { overflowY: 'auto' },
                }}
                rules={[
                  {
                    required: true,
                    message: '请输入正文',
                  },
                ]}
              />
            </ProForm>
          </div>
        )}
      </Modal>

      <Modal
        title={null}
        open={comfirmPop}
        onOk={okComformPop}
        onCancel={closeComformPop}
        okText="覆盖保存"
        cancelText="取消"
        closable={false}
      >
        {comfirmMsg}
        <div>是否继续</div>
      </Modal>
    </div>
  );
};

export default AddKnowledgeModel;
